<?php

namespace app\api\service;

use think\Exception;
use think\Request;

class SmsService extends Api
{
    protected static $instance;
    protected $logName = 'smsLog';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    public function sendSms($data = [])
    {
        $params = array ();

        $security = false;

        $accessKeyId = "LTAI4FyvBmA6EydUySVpyGPm";
        $accessKeySecret = "fV4faRcI2mffmx8CFq0dLtWbyFKfNb";

        $params["PhoneNumbers"] = $data['phone'];

        $params["SignName"] = "锐鹿保";

        $params["TemplateCode"] = isset($data['TemplateCode']) ? $data['TemplateCode'] : "SMS_194790041";

        switch ($params["TemplateCode"])
        {
            case "SMS_194790041":
                $params['TemplateParam'] = Array (
                    "code" => $data['code']
                );
                break;
            case "SMS_203191852":
                $params['TemplateParam'] = Array (
                    "numId" => $data['numId'],
                    "status" => $data['status']
                );
                break;
            case "SMS_203196937":
                $params['TemplateParam'] = Array (
                    "numId" => $data['numId'],
                    "status" => $data['status']
                );
                break;
        }

        $params['OutId'] = 'RL_'.time().rand(10000,99999);

        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = \GuzzleHttp\json_encode($params["TemplateParam"]);
        }

        $helper = new SignatureHelper();

        try{
            $content = $helper->request(
                $accessKeyId,
                $accessKeySecret,
                "dysmsapi.aliyuncs.com",
                array_merge($params, array(
                    "RegionId" => "cn-hangzhou",
                    "Action" => "SendSms",
                    "Version" => "2017-05-25",
                )),
                $security
            );
            LogService::getInstance()->writeLogInfo([
                'content' => $content
            ], $this->logName);
            return true;
        }catch (Exception $e)
        {
            LogService::getInstance()->writeLogInfo([
                'error' => $e->getMessage()
            ], $this->logName);
            return false;
        }
    }
}